<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button onclick="debounce(sayHi,2000)">123456</button>
    <button onclick="throttle(sayHi, 2000)">123456</button>
    <input type="text" id="input" oninput="sayHi()" />
    <input type="text" id="input2" />
    <script>
      //防抖函数
      // function debounce(fn, delay) {
      //   var timer = null;
      //   return function () {
      //     var context = this;
      //     var args = arguments;
      //     clearTimeout(timer);
      //     timer = setTimeout(function () {
      //       fn.apply(context, args);
      //     }, delay);
      //   };
      // }
      //
      // 防抖函数
      function debounce(fn, delay) {
        var timer = null;
        return function () {
          var context = this;
          var args = arguments;
          clearTimeout(timer); //结束上次执行，不然会出现重复执行
          timer = setTimeout(function () {
            fn.apply(context, args);
          }, delay);
        };
      }

      // 节流函数
      function throttle(fn, delay) {
        var timer = null;
        return function () {
          var context = this;
          var args = arguments;
          if (!timer) {
            timer = setTimeout(function () {
              fn.apply(context, args);
              timer = null;
            }, delay);
          }
        };
      }
      var inp = document.getElementById("input2");
      inp.addEventListener("input", test); // 防抖
      function sayHi() {
        console.log("防抖成功");
      }
      function test() {
        console.log("123");
        debounce(sayHi, 500);
        // throttle(sayHi, 2000)();
      }

      // console.log(counter.getCount());
      console.log(count);
    </script>
  </body>
</html>
